<?php

// +----------------------------------------------------------------------
// | Apprh.Shop
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.apprh.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// +----------------------------------------------------------------------
// | Author: 
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 地区模型
 * Class Area
 * @package app\common\model
 */
class Area extends Model{

    // protected $connection = 'db_config1';

    /**
     * 获取开放地区列表
     *
     * @param int $deep
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getOpenAreaList($deep = 1)
    {
        $condition = [
            'area_open' => 1,
            'area_deep' => $deep
        ];
        $result = Db::connect('dbx.SU')->name('Area')->where($condition)->order('area_sort asc')->select();
        return $result;
    }

    /**
     * 根据一级地区id（省级地区）获取二级地区（市级地区）列表
     *
     * @param int $pid
     * @return mixed
     */
    public function getOpenAreaByPid($pid = 0)
    {
        $condition = [
            'area_open' => 1,
            'area_parent_id' => $pid
        ];
        $result = Db::connect('dbx.SU')->name('Area')->where($condition)->order('area_sort asc')->select();
        return $result;
    }

    /**
     * 根据地区id获取地区名称
     *
     * @param int $areaId 地区id
     * @param int $deep 地区级别 1-省级 2-市级 3-区县级
     * @return mixed
     */
    public function getAreaNameById($areaId, $deep = 1)
    {
        $map = [
            'area_id' => $areaId,
            'area_deep' => $deep
        ];
        $result = Db::connect('dbx.SU')->name('Area')->where($map)->value('area_name');
        return $result;
    }

    /**
     * 根据地区名称获取地区id
     * @param string $areaName 地区名称
     * @param int $deep 地区级别 1-省级 2-市级 3-区县级
     * @return mixed
     */
    public function getAreaIdByName($areaName, $deep = 1)
    {
        $map = [
            'area_name' => $areaName,
            'area_deep' => $deep
        ];
        $result = Db::connect('dbx.SU')->name('Area')->where($map)->value('area_id');
        return $result;
    }

    /** 返回某个字段的值
     * @param $where 查询条件
     * @param string $field 查询字段
     * @return mixed
     */
    public function getValue($where, $field="*"){
        return Db::connect('dbx.SU')->name('Area')->where($where)->value($field);
    }

    /** 查询某一列的值 返回数组
     * @param $where 查询条件
     * @param string $field 指定索引
     * @return mixed
     */
    public function getColumn($where, $field="*"){
        return Db::connect('dbx.SU')->name('Area')->where($where)->column($field);
    }

  /**查询一条数据
     * @param $where
     * @param string $field
     * @return array|false|\PDOStatement|string|Model
     */
  public function getOneDarry($where, $field="*"){
      $returndata = [];
      $data = Db::connect('dbx.SU')->name('Area')->where($where)->field($field)->find();
      if(!empty($data)){
          $returndata = $data->toArray();
      }
      return $returndata;
  }
  
  //列表数据
  public function getLists($where = 1, $order = ['area_sort'], $field = "*", $limit = 20){
     $lists = Db::connect('dbx.SU')->name('Area')->where($where)->order($order)->field($field)->limit(config('pageSize') ?? $limit)->select();
     $return_lists = [];
     foreach ($lists as $k => $v){
         $return_lists[$k] = $v->toArray();
     }
     return $return_lists;
  }

  //分页数据
  public function getPageLists($where = 1, $order = ['area_sort'], $field = "*", $p = 20){
    $lists = Db::connect('dbx.SU')->name('Area')->where($where)->order($order)->paginate(config('pageSize') ?? $p,false,['query' => request()->get()]);
    $page = $lists->render();
    $return_lists = [];
   foreach ($lists as $k => $v){
       $return_lists[$k] = $v->toArray();
   }
   return [$return_lists, $page];
  }

    /**
     * 获取用于前端js使用的全部地址数组
     *
     * @return array
     */
    public function getAreaArrayForJson($src = 'cache') {
        if ($src == 'cache') {

            $data = $this->getCache();
        } else {
            $data = $this->_getAllArea();
        }

        $arr = array();
        foreach ($data['children'] as $k => $v) {
            foreach ($v as $vv) {
                $arr[$k][] = array($vv, $data['name'][$vv]);
            }
        }
        return $arr;
    }

    /**
     * 获取地区数组 格式如下
     * array(
     *   'name' => array(
     *     '地区id' => '地区名称',
     *     // ..
     *   ),
     *   'parent' => array(
     *     '子地区id' => '父地区id',
     *     // ..
     *   ),
     *   'children' => array(
     *     '父地区id' => array(
     *       '子地区id 1',
     *       '子地区id 2',
     *       // ..
     *     ),
     *     // ..
     *   ),
     *   'region' => array(array(
     *     '华北区' => array(
     *       '省级id 1',
     *       '省级id 2',
     *       // ..
     *     ),
     *     // ..
     *   ),
     * )
     *
     * @return array
     */
    protected function getCache() {
        // 对象属性中有数据则返回
        if ($this->cachedData !== null)
            return $this->cachedData;

        // 缓存中有数据则返回
        if ($data = rkcache('area')) {
            $this->cachedData = $data;
            return $data;
        }

        // 查库
        $data = $this->_getAllArea();
        wkcache('area', $data);
        $this->cachedData = $data;

        return $data;
    }

    protected $cachedData;

    private function _getAllArea() {
        $data = array();
        $area_all_array = Db::connect('dbx.SU')->name('Area')->limit(false)->select();
        foreach ((array) $area_all_array as $a) {
            $data['name'][$a['area_id']] = $a['area_name'];
            $data['parent'][$a['area_id']] = $a['area_parent_id'];
            $data['children'][$a['area_parent_id']][] = $a['area_id'];
        
            if ($a['area_deep'] == 1 && $a['area_region'])
                $data['region'][$a['area_region']][] = $a['area_id'];
        }
        return $data;
    }
    /**
     * 获取地址详情
     *
     * @return mixed
     */
    public function getAreaInfo($condition = array(), $fileds = '*') {
        return Db::connect('dbx.SU')->name('Area')->where($condition)->field($fileds)->find();
    }
    /**
     * 递归取得本地区及所有上级地区名称
     * @return string
     */
    public function getTopAreaName($area_id,$area_name = '') {
        $info_parent = $this->getAreaInfo(array('area_id'=>$area_id),'area_name,area_parent_id');
        if ($info_parent) {
            return $this->getTopAreaName($info_parent['area_parent_id'],$info_parent['area_name']).' '.$info_parent['area_name'];
        }
    }

}














